﻿$.fn.SmartFormSubmit = function (args, callback) {
    var settings = {
        url: null,
        target: null
    }
    $.extend(settings, args);
    var form = $(this);
    settings.target.click(function () {

        form.validateForm(function (f) {
            if (f) {
                $.post(settings.url, form.serialize(), function (data) {
                    var msg = eval("(" + data + ")");
                    if (callback != undefined) {
                        callback(msg);
                    } else {
                        //msg.Success|msg.Message|msg.ToUrl|msg.ErrorFields|
                        if (msg.Success && msg.ToUrl != "" && msg.ToUrl != "null") {
                            alert("操作成功，点击确定后跳转！");
                            window.location = "/" + msg.ToUrl;
                        } else {
                            alert(msg.Message);
                        }
                    }
                });
            }
        });


    });
}

$.fn.validateForm = function (callback) {
    var isOk = true;
    $(this).find("[validate]").each(function () {
        switch ($(this).attr("validate").toLowerCase()) {
            case "email":
                var email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                if (!email.test($(this).val())) {
                    alert("电子邮件格式错误");
                    $(this).focus();
                    isOk = false;
                    return false;
                }
                break;
            case "mobile":
                var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/;
                if (!mobile.test($(this).val())) {
                    alert("手机号码格式错误");
                    $(this).focus();
                    isOk = false;
                    return false;
                }
                break;
            case "zipcode":
                var zipcode = /^[0-9]{6}$/;
                if (!zipcode.test($(this).val())) {
                    alert("邮政编码格式错误");
                    $(this).focus();
                    isOk = false;
                    return false;
                }
                break;
            case "userno":
                var userno = /^([a-zA-Z0-9]+)$/;
                if (!userno.test($(this).val())) {
                    alert("用户名格式错误，只能输入数字和字母(字符A-Z, a-z, 0-9)");
                    $(this).focus();
                    isOk = false;
                    return false;
                }
            
        }
    });
    if (isOk && callback != undefined) {
        callback(isOk);
    }
}